package com.ruslan.magaz.web;
 
import java.io.IOException;
import java.text.DateFormat;
import java.util.Date;
import java.util.List;
import java.util.Locale;
 










import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.servlet.mvc.support.RedirectAttributes;

import com.ruslan.magaz.domain.Cart;
import com.ruslan.magaz.domain.Category;
import com.ruslan.magaz.domain.User;
import com.ruslan.magaz.service.ItemService;
import com.ruslan.magaz.service.UserService;
 
/**
 * Handles requests for the application home page.
 */
@Controller
public class HomeController {
     
     
    /**
     * Simply selects the home view to render by returning its name.
     */
	@Autowired
	private ItemService itemService;
	@Autowired
	private UserService userService;
	
	@ModelAttribute("categories")
	 public List<Category> getAllCategories() {
	  return itemService.getAllCategories();
	}
	
	@ModelAttribute("user")
	 public User getUser(HttpServletRequest req) throws Exception {
		HttpSession session = req.getSession(false);
		if (session == null){
			return new User();
		}
		Object currentUserId = session.getAttribute("userId");
		if (currentUserId == null){
			return new User();
		}
		
		return userService.getUserById((Integer) currentUserId);
	}
	
    @RequestMapping(value = {"/home", "/"}, method = RequestMethod.GET)
    public String home(HttpServletRequest req, Locale locale, Model model) {
         
        Date date = new Date();
        DateFormat dateFormat = DateFormat.getDateTimeInstance(DateFormat.LONG, DateFormat.LONG, locale);
         
        String formattedDate = dateFormat.format(date);
         
        model.addAttribute("serverTime", formattedDate );
//        model.addAttribute("categories",getAllCategories());
        return "tiles/home";

    }
    
    @RequestMapping(value = "/login", method = RequestMethod.GET)
	public void login() {

	}
    
    @RequestMapping(value="/login", method = RequestMethod.POST)
    public String logInPost(HttpServletRequest req, HttpServletResponse res, @RequestParam("login") String login, @RequestParam("password") String password, Model model, RedirectAttributes redir) throws ServletException, IOException{
	        
	        // TODO Auto-generated method stub
	        //String login = @RequestParam("login") String login;
	        //String pass = req.getParameter("pass");
	        User thisUser = userService.login(login, password);
	        String referer = req.getHeader("Referer");
	        if (thisUser != null){
	            //HttpServletRequest httpReq = (HttpServletRequest) req;
	            HttpSession session = req.getSession(true);
	            session.setAttribute("userId", thisUser.getUserId());
//	            model.addAttribute("user", thisUser);
	        }else{
//	        	model.addAttribute("loginError", true);
	        	redir.addFlashAttribute("loginError",true);
	        	return "redirect:home/";
	        }
	        if(thisUser.getRole().getRoleId()==1){
	        	return "redirect:"+ referer;
	        }else{
	        	return "redirect:/admin";
	        }
	 }
    
    @RequestMapping(value="/admin")
    public	String adminView(HttpServletRequest req, HttpServletResponse res,  Model model) throws ServletException, IOException{
		 return "adminTiles/adminCategories";
	 }
    
 @RequestMapping(value="/logout")
    public	String logInPost(HttpServletRequest req, HttpServletResponse res,  Model model) throws ServletException, IOException{
	        
	        // TODO Auto-generated method stub
	        //String login = @RequestParam("login") String login;
	        //String pass = req.getParameter("pass");
		 HttpSession session = req.getSession(false);
		 if (session != null) {
		     session.invalidate();
		 }
		 return "redirect:/home";
	 }
}